import React, { Component } from "react";
import { BrowserRouter as Router, Route, Switch, Link, } from "react-router-dom";
import {
    Layout, Card, message, Empty, Form, List, Select, Divider, Icon, Tag, Skeleton
} from "antd";
import { WingBlank, WhiteSpace, PullToRefresh, Flex, ActivityIndicator } from 'antd-mobile';
import {
    getDeviceInfoListApi, getHistoryEleOrTemApi, getRecentDeviceInfoApi, getChartTemperatureApi, getChartElectricApi,
} from "../js/api.js";

import { iconFontUrl } from "../js/config.js";
import moment from 'moment';
import $ from 'jquery';

const { Content, Sider, Header } = Layout;
// import echarts from 'echarts';
import * as echarts from 'echarts'
const FormItem = Form.Item;
const Option = Select.Option;
const IconFont = Icon.createFromIconfontCN({
    scriptUrl: iconFontUrl,
});


class Electricalsafety extends Component {
    constructor(props) {
        super(props);
        this.state = {
        };
    }

    render() {
        return (
            <Router basename="/electricalsafety">
                <Layout style={{ backgroundColor: '#f5f5f5' }}>
                    <Content>
                        <Switch>
                            <Route path="/condition" component={ElectricalsafetySearch} />
                            <Route path="/detailchart" component={ChartEleAndTemSearch} />
                            <Route path="/" component={(props) => (<ElectricalsafetyList {...props} />)} />
                        </Switch>
                    </Content>
                </Layout>
            </Router>
        );
    }
}

class ElectricalsafetyList extends Component {
    constructor(props) {
        super(props);
        this.state = {
            tableLoading: false,
            columnData: [],
            sum: null,
            normaltem: null,
            normalele: null,
            render: false,
            departmentId: this.getUrlParam("departmentId"),
        };
    }

    componentDidMount() {
        this.setState({
            tableLoading: true
        });
        let columnData = [];
        let sum = 0;
        let work = 0;
        getRecentDeviceInfoApi(this.state.departmentId)
            .then((res) => {
                for (let key in res.data.data) {
                    let isWork = (new Date().getTime() - Math.max(res.data.data[key].temperatureTime, res.data.data[key].electricTime)) < 600000 ? true : false;
                    columnData.push({
                        nowElectric: res.data.data[key].nowElectric,
                        address: key,
                        name: res.data.data[key].name,
                        nowTemperature: res.data.data[key].nowTemperature,
                        electricThreshold: res.data.data[key].electricThreshold,
                        temperatureThreshold: res.data.data[key].temperatureThreshold,
                        temperatureTime: res.data.data[key].temperatureTime,
                        electricTime: res.data.data[key].electricTime,
                        work: isWork
                    });
                    if (isWork) {
                        work++;
                    }
                    sum++
                }
                this.setState({
                    columnData: columnData,
                    tableLoading: false,
                    sum: sum,
                    normaltem: res.data.normaltem,
                    normalele: res.data.normalele,
                    render: true,
                    work: work
                });
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }

    getUrlParam(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
        var r = window.location.search.substr(1).match(reg);  //匹配目标参数
        if (r != null) return unescape(r[2]);
        return null; //返回参数值
    }

    onClick = (name, imei, electricThreshold, temperatureThreshold) => {
        this.props.history.push({ pathname: "/condition", state: { name, imei, electricThreshold, temperatureThreshold } })
    }

    render() {
        if (this.state.render == true) {
            let List = this.state.columnData.map(val => {
                let isWork = val.work ? null : <Tag color="red">未工作</Tag>
                // console.log(val.temperatureTime, val.electricTime, "++++++++++")
                return (
                    <div>
                        <Card
                            size="small"
                            title={
                                <div style={{ color: "#E9AE6A" }}>
                                    {val.name}
                                    <Divider type="vertical" style={{ width: "2px" }} />
                                    {"IMEI: " + val.address}
                                </div>}
                            extra={<span style={{ colcor: "grey" }}>查看详情</span>}
                            style={{ background: "#F5F6EB", borderRadius: "8px", width: "98%", marginLeft: "1%", marginTop: "2px" }}
                            headStyle={{ height: "20px" }}
                            bodyStyle={{ height: "115px", padding: 12, width: "100%" }}
                            onClick={() => this.onClick(val.name, val.address, val.electricThreshold, val.temperatureThreshold)}
                        >
                            <div><span>{"反馈时间: " + new Date(val.electricTime).toLocaleString()}</span><Divider type="vertical" />{isWork}</div>
                            <TemAndEleListCharts nowElectric={val.nowElectric} nowTemperature={val.nowTemperature} electricThreshold={val.electricThreshold} temperatureThreshold={val.temperatureThreshold} chartsname={val.address} />
                        </Card>
                    </div>)
            })
            let height = window.screen.availHeight - 278;
            return (
                <div>
                    <div style={{ height: "270px" }}>
                        <TemAndEleListDashBoard sum={this.state.sum} work={this.state.work} normalele={this.state.normalele} />
                    </div>
                    <div className="innerbox"
                        style={{
                            width: "100%",
                            marginTop: 3,
                            height: height
                        }}>
                        {List}
                    </div>
                </div>
            )
        } else { return (null) }
    }
}

class TemAndEleListDashBoard extends Component {
    constructor(props) {
        super(props);
        // console.log(props)
        this.state = {
            sum: props.sum,
            work: props.work,
            normalele: props.normalele,
        };
    }

    componentDidMount() {
        this.drawChart();
    }

    drawChart() {
        const { sum, work, normalele } = this.state
        let valuework = work * 100 / sum
        let valueele = normalele * 100 / sum
        var highlight = 'white';
        let chart = echarts.init(document.getElementById('TemAndEleListDashBoard'));
        if (sum != null) {
            var demoData = [
                {
                    name: '正常工作设备比',
                    value: valuework,
                    value1: work,
                    unit: sum,
                    pos: ['25%', '65%'],
                    range: [0, 100],
                    colora: 'rgba(193,136,244,0.9)',
                    colorb: 'rgba(90,245,128,0.6)'
                }, {
                    name: '电流正常比',
                    value: valueele,
                    value1: normalele,
                    unit: sum,
                    pos: ['75%', '65%'],
                    range: [0, 100],
                    colora: 'rgba(193,136,244,0.9)',
                    colorb: 'rgba(242,166,200,0.6)'
                }

            ];

            chart.setOption({
                backgroundColor: '#212121',
                title: {
                    text: '设备用电安全情况',
                    subtext: '当前数据获取时间:' + new Date().toLocaleString(),
                    left: '50%',
                    top: '10%',
                    textAlign: 'center',
                    textStyle: {
                        color: "#fff",
                        fontSize: 14,
                    },
                    subtextStyle: {
                        color: "#fff",
                        fontSize: 12,
                    }
                },
                series: (function () {
                    var result = [];

                    demoData.forEach(function (item) {
                        result.push(
                            // 内侧指针、数值显示
                            {
                                name: item.name,
                                type: 'gauge',
                                center: item.pos,
                                radius: '60%',
                                startAngle: 225,
                                endAngle: -45,
                                min: 0,
                                max: 100,
                                axisLine: {
                                    show: true,
                                    lineStyle: {
                                        width: 2,
                                        color: [
                                            [
                                                item.value / 100, new echarts.graphic.LinearGradient(
                                                    0, 0, 1, 0, [{
                                                        offset: 0,
                                                        color: 'rgba(255,255,255,0)',
                                                    },
                                                    {
                                                        offset: 1,
                                                        color: 'white',
                                                    }
                                                ]
                                                )
                                            ],
                                            [
                                                1, 'rgba(255,255,255, 0)'
                                            ]
                                        ]
                                    }
                                },
                                axisTick: {
                                    show: 0,
                                },
                                splitLine: {
                                    show: 0,
                                },
                                axisLabel: {
                                    show: 0
                                },
                                pointer: {
                                    show: 0,
                                },
                                detail: {
                                    show: 0
                                },
                                data: [{
                                    value: item.value,
                                }]
                            },
                            // 外围刻度
                            {
                                type: 'gauge',
                                center: item.pos,
                                radius: '50%', // 1行3个
                                splitNumber: item.splitNum || 10,
                                min: 0,
                                max: 100,
                                startAngle: 225,
                                endAngle: -45,
                                axisLine: {
                                    show: true,
                                    lineStyle: {
                                        width: 1,
                                        color: [
                                            [1, 'rgba(0,0,0,0)']
                                        ]
                                    }
                                }, //仪表盘轴线
                                axisTick: {
                                    show: true,
                                    lineStyle: {
                                        color: 'rgba(255,255,255,0.6)',
                                        width: 1
                                    },
                                    length: -4
                                }, //刻度样式
                                splitLine: {
                                    show: true,
                                    length: 5,
                                    lineStyle: {
                                        color: 'rgba(255,255,255,0.6)'
                                    }
                                }, //分隔线样式
                                axisLabel: {
                                    show: true,
                                    distance: 1,
                                    textStyle: {
                                        color: highlight,
                                        fontSize: '0',
                                        fontWeight: 'bold'
                                    }
                                },
                                pointer: {
                                    show: 0
                                },
                                detail: {
                                    show: 0
                                }
                            },

                            // 内侧指针、数值显示
                            {
                                name: item.name,
                                type: 'gauge',
                                center: item.pos,
                                radius: '54%',
                                startAngle: 225,
                                endAngle: -45,
                                min: 0,
                                max: 100,
                                axisLine: {
                                    show: true,
                                    lineStyle: {
                                        width: 30,
                                        color: [
                                            [
                                                item.value / 100, new echarts.graphic.LinearGradient(
                                                    0, 0, 1, 0, [{
                                                        offset: 0,
                                                        color: 'rgba(0,0,0, 0)',
                                                    },
                                                    {
                                                        offset: 1,
                                                        color: item.colorb,
                                                    }
                                                ]
                                                )
                                            ],
                                            [
                                                1, 'rgba(255,255,255, 0)'
                                            ]
                                        ]
                                    }
                                },
                                axisTick: {
                                    show: 0,
                                },
                                splitLine: {
                                    show: 0,
                                },
                                axisLabel: {
                                    show: 0
                                },
                                pointer: {
                                    show: true,
                                    length: '102%',
                                    width: 3
                                },
                                title: {
                                    show: true,
                                    offsetCenter: [0, '65%'],
                                    color: 'white',
                                    fontSize: 11,
                                    /* backgroundColor: "#D8d8d8",*/
                                    borderRadius: 21,
                                    padding: 5
                                },
                                detail: {
                                    show: true,
                                    offsetCenter: [0, 20],
                                    textStyle: {
                                        fontSize: 9,
                                        color: '#fff'
                                    },
                                    formatter: [
                                        (item.value1) + '/' + (item.unit || ''),
                                        /* '{name|' + item.name + '}'*/
                                    ].join('\n'),

                                    rich: {
                                        name: {
                                            fontSize: 10,
                                            lineHeight: 10,
                                            color: '#ddd',
                                            padding: [30, 0, 0, 0]
                                        }
                                    }
                                },
                                itemStyle: {
                                    normal: {
                                        color: highlight,
                                    }
                                },
                                data: [{
                                    value: item.value,
                                    name: item.name
                                }]
                            }
                        );
                    });

                    return result;
                })()
            })
        }
    }

    render() {
        return (<div id='TemAndEleListDashBoard' style={{ height: '100%', width: '100%' }} />)
    }
}

class TemAndEleListCharts extends Component {
    constructor(props) {
        super(props);
        // console.log(props, "++++++++++++++")
        this.state = {
            wendu: props.nowTemperature,
            dianliu: props.nowElectric,
            temperatureThreshold: props.temperatureThreshold,
            electricThreshold: props.electricThreshold,
            chartsname: props.chartsname
        };
    }

    componentDidMount() {
        this.drawChart();
    }

    drawChart() {
        const { temperatureThreshold, electricThreshold, wendu, dianliu } = this.state
        if (wendu != null) {
            let chart = echarts.init(document.getElementById(this.state.chartsname));
            let color1 = '#77C34F'
            let color2 = '#FFB5A1'
            let myColor = [];

            if (temperatureThreshold > wendu) {
                myColor.push(color1)
            } else { myColor.push(color2) }
            if (electricThreshold > dianliu) {
                myColor.push(color1)
            } else { myColor.push(color2) }

            chart.setOption({
                grid: {
                    top: "1%",
                    bottom: "1%",
                    left: 60,
                    right: 60,
                    // containLabel: true
                },
                xAxis: [{
                    show: false,
                }],
                yAxis: [{
                    axisTick: 'none',
                    axisLine: 'none',
                    offset: '6',
                    axisLabel: {
                        textStyle: {
                            color: '#000000',
                            fontSize: '14',
                        }
                    },
                    data: ['温度', '电流']
                }, {
                    axisTick: 'none',
                    axisLine: 'none',
                    axisLabel: {
                        textStyle: {
                            color: '#000000',
                            fontSize: '14',
                        }
                    },
                    data: [wendu.toFixed(2) + "℃", dianliu + "mA"]
                }, {
                    axisLine: {
                        lineStyle: {
                            color: 'rgba(0,0,0,0)'
                        }
                    },
                    data: [],
                }],
                series: [{
                    name: '条',
                    type: 'bar',
                    yAxisIndex: 0,
                    data: [(this.state.wendu * 98 / this.state.temperatureThreshold) > 98 ? 98 : (this.state.wendu * 98 / this.state.temperatureThreshold), 98],
                    label: {
                        normal: {
                            show: false,
                            position: 'right',
                            textStyle: {
                                color: '#ffffff',
                                fontSize: '14',
                            }
                        }
                    },
                    barWidth: 6,
                    itemStyle: {
                        normal: {
                            color: function (params) {
                                var num = myColor.length;
                                return myColor[params.dataIndex % num]
                            },
                        }
                    },
                    z: 2
                }, {
                    name: '白框',
                    type: 'bar',
                    yAxisIndex: 1,
                    barGap: '-100%',
                    data: [99.4, 99.5],
                    barWidth: 10,
                    itemStyle: {
                        normal: {
                            color: '#ffffff',
                            barBorderRadius: 20,
                        }
                    },
                    z: 1
                }, {
                    name: '外框',
                    type: 'bar',
                    yAxisIndex: 2,
                    barGap: '-100%',
                    data: [100, 100],
                    barWidth: 13,
                    itemStyle: {
                        normal: {
                            color: function (params) {
                                // var num = myColor.length;
                                return '#C9CABB'
                            },
                            barBorderRadius: 20,
                        }
                    },
                    z: 0
                },
                {
                    name: '外圆',
                    type: 'scatter',
                    hoverAnimation: false,
                    data: [0, 0],
                    yAxisIndex: 2,
                    symbolSize: 20,
                    itemStyle: {
                        normal: {
                            color: function (params) {
                                var num = myColor.length;
                                return myColor[params.dataIndex % num]
                            },
                            opacity: 1,
                        }
                    },
                    z: 2
                }]
            });
        }
    }

    render() {
        return (<div id={this.state.chartsname} style={{ height: '100%', width: '100%' }} />)
    }
}

class ElectricalsafetySearch extends Component {
    constructor(props) {
        super(props);
        this.state = {
            data: [],
            loading: true,
            currentListData: [],
            scrollLoading: false,

            type: 'ele',
            name: this.props.location.state.name,
            imei: this.props.location.state.imei,
            electricThreshold: this.props.location.state.electricThreshold,
            temperatureThreshold: this.props.location.state.temperatureThreshold,
            // endTime: this.props.name == undefined ? undefined : moment(),
            // startTime: this.props.name == undefined ? undefined : moment().add('hours', -4),
        };
        console.log("ElectricalsafetySearch", this.props.location.state.name)
    }

    componentDidMount() {
        this.refreshData();
    }

    refreshData() {
        this.setState({
            loading: true,
        })
        getHistoryEleOrTemApi(this.state.imei, this.state.type,
            this.state.type == 'ele' ? this.state.electricThreshold : this.state.temperatureThreshold)
            .then((res) => {
                let data = [];
                let currentListData = [];
                res.data.forEach((item, index) => {
                    data.push({
                        key: index + 1,
                        timeStart: item.timeStart,
                        timeEnd: item.timeEnd,
                        max: item.max,
                    });
                });

                if (data.length > 5) {
                    currentListData = data.slice(0, 5);
                } else {
                    currentListData = data.slice(0, data.length);
                }

                this.setState({
                    data: data,
                    currentListData: currentListData,
                    loading: false,
                });
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }

    switchType = () => {
        if (this.state.type == 'ele') {
            this.setState({
                type: 'tem',
                scrollLoading: false,
            }, () => {
                this.refreshData();
                $('.am-pull-to-refresh').animate({
                    scrollTop: $(".am-pull-to-refresh-content-wrapper").offset().top
                }, 1000);
            })
        } else {
            this.setState({
                type: 'ele',
                scrollLoading: false,
            }, () => {
                this.refreshData();
                $('.am-pull-to-refresh').animate({
                    scrollTop: $(".am-pull-to-refresh-content-wrapper").offset().top
                }, 1000);
            })
        }
    }

    listRefresh = () => {
        this.setState({
            scrollLoading: true,
        }, () => {
            let data = [...this.state.data];
            let currentListData = [...this.state.currentListData];
            setTimeout(() => {
                if (data.length == currentListData.length) {
                    message.info('已经到底了~');
                    this.setState({
                        scrollLoading: false,
                    });
                } else if (data.length - currentListData.length <= 5) {
                    this.setState({
                        currentListData: data,
                        scrollLoading: false,
                    })
                } else {
                    this.setState({
                        currentListData: currentListData.concat(...[data.slice(currentListData.length, currentListData.length + 5)]),
                        scrollLoading: false,
                    });
                }
            }, 500);
        });
    }

    getUrlParam(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
        var r = window.location.search.substr(1).match(reg);  //匹配目标参数
        if (r != null) return unescape(r[2]);
        return null; //返回参数值
    }

    render() {
        const pathname = this.props.history.location.pathname;

        let cardList;
        if (this.state.currentListData.length != 0) {
            cardList = this.state.currentListData.map((value, index) => {
                let threshold = this.state.type == 'ele' ? this.state.electricThreshold : this.state.temperatureThreshold;
                let listData = [
                    {
                        title: '时间段',
                        description: (
                            <div>
                                {moment(value.timeStart).format('YYYY-MM-DD HH:mm')}
                                {' ~ '}
                                {moment(value.timeEnd).format('YYYY-MM-DD HH:mm')}
                            </div>
                        )
                    }, {
                        title: this.state.type == 'ele' ? '电流最大值/阈值(mA)' : '温度最大值/阈值(℃)',
                        description: (
                            <div>
                                {value.max >= threshold ? (
                                    <span style={{ color: 'red', fontWeight: 500 }}>{value.max}</span>
                                ) : value.max}
                                /
                                {threshold}
                            </div>
                        )
                    },
                ];
                return (
                    <Link
                        style={{ textDecoration: 'none' }}
                        to={{
                            pathname: '/detailchart',
                            state: {
                                imei: this.state.imei,
                                timeStart: value.timeStart,
                                timeEnd: value.timeEnd,
                                type: this.state.type
                            }
                        }}>
                        <Card
                            className='conditionCard'
                            style={{ marginBottom: 10 }}
                            headStyle={{ padding: '0 16px' }}
                            bodyStyle={{ padding: '0 16px' }}
                            title={"序号: " + value.key}
                            size='small'
                            extra={(
                                <span style={{ fontSize: 14, color: '#1890ff' }}>
                                    {'可视图表 >'}
                                </span>
                            )}>

                            <List
                                itemLayout="horizontal"
                                dataSource={listData}
                                renderItem={item => (
                                    <List.Item>
                                        <List.Item.Meta
                                            title={item.title}
                                            description={item.description}
                                        />
                                    </List.Item>
                                )}
                            />
                        </Card>
                    </Link>
                )
            })
        } else {
            cardList = (<Empty />);
        }


        return (
            <div>
                <PullToRefresh
                    style={{
                        height: document.documentElement.clientHeight,
                        overflow: 'auto',
                    }}
                    damping={60}
                    ref={el => this.ptr = el}
                    indicator={{ deactivate: '上拉可以刷新', }}
                    direction={'up'}
                    refreshing={this.state.scrollLoading}
                    onRefresh={this.listRefresh}>
                    <Divider>设备信息</Divider>
                    <div style={{ marginLeft: 10, marginRight: 10, textAlign: 'center' }}>
                        <Card
                            style={{ marginBottom: 10 }}
                            className='conditionCard'
                            title={'设备地址'}
                            size='small'
                        >{this.state.name}</Card>
                        <Card
                            className='conditionCard'
                            title={'IMEI'}
                            size='small'
                        >{this.state.imei}</Card>
                    </div>

                    {this.state.loading ?
                        (
                            <ActivityIndicator toast text="加载中..." />
                        ) : (
                            <div>
                                <Divider>数据列表</Divider>
                                {cardList}
                            </div>
                        )}
                </PullToRefresh>
                {pathname == '/condition' ? (
                    <div
                        className='hoverButtom'
                        style={{
                            width: 100,
                            height: 40,
                            borderRadius: 20,
                            textAlign: 'center',
                            backgroundColor: '#99999966'
                        }}
                        onClick={this.switchType}>
                        <div
                            style={{
                                width: '100%',
                                height: '100%',
                                margin: '-14px auto 0',
                                position: 'relative',
                                top: '50%',
                            }}>
                            {this.state.type == 'ele' ?
                                (
                                    <div>
                                        <span style={{ color: '#1890ff', fontSize: 18, fontWeight: 500 }}>电流</span>
                                        <span style={{ color: '#000000', fontSize: 18, fontWeight: 500 }}>{' / '}</span>
                                        <span style={{ color: '#333333', fontSize: 12, }}>温度</span>
                                    </div>
                                ) : (
                                    <div>
                                        <span style={{ color: '#333333', fontSize: 12, }}>电流</span>
                                        <span style={{ color: '#000000', fontSize: 18, fontWeight: 500 }}>{' / '}</span>
                                        <span style={{ color: '#1890ff', fontSize: 18, fontWeight: 500 }}>温度</span>
                                    </div>
                                )}
                        </div>
                    </div>
                ) : null}
            </div>
        )
    }
}



class ChartEleAndTemSearch extends Component {
    constructor(props) {
        super(props);

        let winWidth;
        // 获取窗口宽度
        if (window.innerWidth)
            winWidth = window.innerWidth;
        else if ((document.body) && (document.body.clientWidth))
            winWidth = document.body.clientWidth;

        this.state = {
            chartData: {},

            imei: this.props.location.state.imei,
            timeStart: this.props.location.state.timeStart,
            timeEnd: this.props.location.state.timeEnd,
            type: this.props.location.state.type,

            winWidth: winWidth,
            titleText: '',
            yAxisName: '',
            loading: true
        };
        // console.log(this.state.chartData, "!!!!!!!!!!!!!!!!!!!!!!!!")
    }

    componentDidMount() {
        if (this.state.type == 'tem') {
            this.setState({
                titleText: '温度',
                yAxisName: '温度(℃)'
            }, () => {
                this.refreshDataTem();
            })
        } else if (this.state.type == 'ele') {
            this.setState({
                titleText: '电流',
                yAxisName: '电流(mA)'
            }, () => {
                this.refreshDataEle();
            })
        }
    }

    refreshDataEle() {
        this.setState({
            loading: true
        });
        getChartElectricApi(this.state.imei, this.state.timeStart, this.state.timeEnd)
            .then((res) => {
                let data = { ...res.data };
                data.data.unshift(0);
                data.data.push(0);

                data.status.unshift(0);
                data.status.push(0);

                data.thresHold.unshift(data.thresHold[0]);
                data.thresHold.push(data.thresHold[0]);

                data.time.unshift(moment(data.time[0]).add('minutes', -1).format('YYYY-MM-DD HH:mm:ss'));
                data.time.push(moment(data.time[data.time.length - 1]).add('minutes', 1).format('YYYY-MM-DD HH:mm:ss'));

                this.setState({
                    chartData: data,
                    loading: false
                }, () => { this.drawChart(); });
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }

    refreshDataTem() {
        this.setState({
            loading: true
        });
        getChartTemperatureApi(this.state.imei, this.state.timeStart, this.state.timeEnd)
            .then((res) => {
                let data = [...res.data];
                data.data.unshift(0);
                data.data.push(0);

                data.status.unshift(0);
                data.status.push(0);

                data.thresHold.unshift(data.thresHold[0]);
                data.thresHold.push(data.thresHold[0]);

                data.time.unshift(moment(data.time[0]).add('minutes', -1));
                data.time.push(moment(data.time[data.time.length - 1]).add('minutes', 1));

                this.setState({
                    chartData: data,
                    loading: false
                }, () => { this.drawChart(); });
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }


    drawChart() {
        if (JSON.stringify(this.state.chartData) != '{}') {
            // console.log(this.state.chartData);
            let chart = echarts.init(document.getElementById('chartEleAndTemSearch'));

            let dataZoom = [{
                type: 'inside',
                start: 0,
                end: 100
            }, {
                start: 0,
                end: 100,
                handleIcon: 'M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
                handleSize: '80%',
                handleStyle: {
                    color: '#fff',
                    shadowBlur: 3,
                    shadowColor: 'rgba(0, 0, 0, 0.6)',
                    shadowOffsetX: 2,
                    shadowOffsetY: 2
                }
            }];

            // let markPoint = [];
            // for (let i = 0; i < this.state.chartData.troubleTime.length; i++) {
            //     markPoint.push({
            //         name: '警告',
            //         value: this.state.chartData.troubleValue[i],
            //         xAxis: this.state.chartData.troubleTime[i].replace(' ', '\n'),
            //         yAxis: this.state.chartData.troubleValue[i]
            //     })
            // }

            chart.setOption({
                title: {
                    text: '设备' + this.state.titleText + '变化统计图',
                    left: 'center'
                },
                tooltip: {
                    trigger: 'axis'
                },
                legend: {
                    data: ['实际', '阈值'],
                    top: 30
                },
                color: ['#2f4554', '#c23531'],
                grid: {
                    left: '10px',
                    right: '40px',
                    bottom: '40px',
                    top: '80px',
                    containLabel: true
                },
                xAxis: {
                    type: 'category',
                    boundaryGap: false,
                    data: this.state.chartData.time.map(function (str) {
                        return str.replace(' ', '\n')
                    }),
                    axisLabel: {
                        textStyle: {
                            color: '#000000',
                            fontSize: '11',
                        }
                    },
                    // axisLine: { onZero: true },
                },
                yAxis: {
                    name: this.state.yAxisName,
                    type: 'value',
                    scale: true,
                    axisLabel: {
                        textStyle: {
                            color: '#000000',
                            fontSize: '11',
                        }
                    },
                },
                dataZoom: dataZoom,
                series: [{
                    name: '实际',
                    type: 'line',
                    smooth: true,
                    symbol: 'none',
                    data: this.state.chartData.data,
                    areaStyle: {
                        normal: {
                            type: 'default',
                            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                                offset: 0,
                                color: 'rgba(19, 37, 250,0.2)'
                            }, {
                                offset: 1,
                                color: 'rgba(19, 37, 250,0.2)'
                            }], false)
                        }
                    },
                    markLine: {
                        data: [
                            {
                                type: 'average',
                                name: '平均值',
                                label: {
                                    normal: {
                                        position: 'end',
                                        formatter: '平均值\n{c}',
                                        color: '#d48265'
                                    },
                                },
                                lineStyle: {
                                    color: '#d48265'
                                }
                            }, [{
                                symbol: 'none',
                                x: this.state.winWidth - 95,
                                yAxis: 'max'
                            }, {
                                symbol: 'circle',
                                label: {
                                    normal: {
                                        position: 'start',
                                        formatter: '最大值',
                                        color: '#c23531'
                                    },
                                },
                                lineStyle: {
                                    color: '#c23531'
                                },
                                type: 'max',
                                name: '最大值',
                            }]
                            // , [{
                            //     symbol: 'none',
                            //     x: this.state.winWidth - 95,
                            //     yAxis: 'min'
                            // }
                            // , {
                            //     symbol: 'circle',
                            //     label: {
                            //         normal: {
                            //             position: 'start',
                            //             formatter: '最小值',
                            //             color: '#91c7ae'
                            //         },
                            //     },
                            //     lineStyle: {
                            //         color: '#91c7ae'
                            //     },
                            //     type: 'min',
                            //     name: '最小值',
                            // }
                            // ]
                        ]
                    },
                },
                {
                    name: '阈值',
                    type: 'line',
                    symbol: 'none',
                    smooth: true,
                    data: this.state.chartData.thresHold,
                    // markPoint: {
                    //     data: markPoint
                    // },
                }]

            });
            window.onresize = chart.resize;
        }
    }

    render() {
        let chartStyle = {
            height: 300,
        };
        return (
            <div>
                <Divider>可视化图表</Divider>
                <div style={{ background: '#ffffff', padding: '10px 3px' }}>
                    <Skeleton loading={this.state.searchChartLoading} active>
                        <div id='chartEleAndTemSearch' style={chartStyle} />
                    </Skeleton>
                </div>
            </div>
        )
    }
}
export default Electricalsafety;